import { Breadcrumb, Button, Tabs, Row, Col } from 'antd';
import React, { FC } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import _ from 'lodash';
import { PageContainer } from '@/component/page-container';
import BasicTop from '../../component/basicTop';
// eslint-disable-next-line import/no-named-default
import { default as BasicBody, formTpl as basicInfo } from '../../component/basicBody';
import { list as learnExpInfo } from '../change/learnExp';
import styles from '../index.less';
import { TeachersSrv } from '@/service/teacher';
import utils, { getPathRoot } from '@/utils';
import MenuContent from './menu';
import { RESEARCH_TYPE } from '@/constant/teachOptions';

const LearnExp = React.lazy(() => import('@/view/teacher/employed/change/learnExp'));
const WorkExp = React.lazy(() => import('@/view/teacher/employed/change/workExp'));
const PositionAppmt = React.lazy(() => import('@/view/teacher/employed/change/positionAppmt'));
const ProTechMg = React.lazy(() => import('@/view/teacher/employed/change/proTechMg'));
const TeacherQual = React.lazy(() => import('@/view/teacher/employed/change/teacherQual'));
const SkillQual = React.lazy(() => import('@/view/teacher/employed/change/skillQual'));
const TeacherEthics = React.lazy(() => import('@/view/teacher/employed/change/teacherEthics'));
const TeacherEthicsPunishment = React.lazy(() => import('@/view/teacher/employed/change/teacherEthicsPunishment'));
const TearchEdu = React.lazy(() => import('@/view/teacher/employed/change/tearchEdu'));
const OsResearch = React.lazy(() => import('@/view/teacher/employed/change/osResearch'));
const RecrVisit = React.lazy(() => import('@/view/teacher/employed/change/recrVisit'));
const DomesticTraining = React.lazy(() => import('@/view/teacher/employed/change/domesticTraining'));
const AnnualAssess = React.lazy(() => import('@/view/teacher/employed/change/annualAssess'));
const ScientificResearch = React.lazy(() => import('@/view/teacher/employed/change/scientificResearch'));
const TransferInfo = React.lazy(() => import('@/view/teacher/employed/change/transfer'));
const BorrowInfo = React.lazy(() => import('@/view/teacher/employed/change/borrow'));
const WorkChangeInfo = React.lazy(() => import('@/view/teacher/employed/change/workchange'));
const Logs = React.lazy(() => import('@/view/teacher/component/logs'));

const Groups: FC<{ isEdit?: boolean }> = ({ isEdit = true }) => {
  const navigator = useNavigate();
  const [topCntForm, setTopCntForm] = React.useState<any>(null);
  const [topPhotoForm, setTopPhotoForm] = React.useState<any>(null);

  //const location = useLocation();
  const { id } = useParams();
  const [form, setForm] = React.useState({ basicTop: {}, basicBody: {} });
  const [changeInfo, setChangeInfo] = React.useState<Array<any>>([]);
  const [tabKey, setTabKey] = React.useState('1');
  const [showLogs, setShowLogs] = React.useState(false);

  const api = {
    basicTop: {
      save: TeachersSrv.update,
    },
    basicBody: {
      submit: TeachersSrv.infoSubmit,
      save: TeachersSrv.infoSave,
    },
  };

  // 根据 label 获取value
  const getLabelValue = (label: string) => {
    return _.find(RESEARCH_TYPE, { label })?.value;
  };

  // 定义菜单配置数组
  const menus = [
    {
      key: 'basicInfo',
      title: '教职工基本信息',
      subMenu: [],
      content: (
        <div id="baseForm">
          <BasicBody
            isEdit={isEdit}
            buttonList={[<Button onClick={() => navigator(`${getPathRoot()}/employed`)}>返回</Button>]}
            formValue={form.basicBody}
            api={api.basicBody}
          />
        </div>
      ),
    },
    {
      key: 'studyTraining',
      title: '学习/培训信息',
      subMenu: [
        { key: 'learningExperience', title: '学习经历', content: <LearnExp isEditPanel={isEdit} /> },
        { key: 'domesticTraining', title: '国内培训', content: <DomesticTraining isEditPanel={isEdit} /> },
        { key: 'overseasTraining', title: '海外（访学）研修', content: <OsResearch isEditPanel={isEdit} /> },
      ],
    },
    {
      key: 'workInfo',
      title: '工作/聘任信息',
      subMenu: [
        { key: 'workExperience', title: '工作经历', content: <WorkExp isEditPanel={isEdit} /> },
        { key: 'positionResponsibility', title: '岗位聘任', content: <PositionAppmt isEditPanel={isEdit} /> },
        { key: 'technicalResponsibilities', title: '专业技术职务聘任', content: <ProTechMg isEditPanel={isEdit} /> },
        { key: 'communication', title: '交流轮岗', content: <ProTechMg isEditPanel={isEdit} /> },
      ],
    },
    {
      key: 'annualAssessment',
      title: '年度考核信息',
      subMenu: [],
      content: <AnnualAssess isEditPanel={isEdit} />,
    },
    {
      key: 'teacherTitle',
      title: '教师资格/证书信息',
      subMenu: [
        { key: 'qualification', title: '教师资格信息', content: <TeacherQual isEditPanel={isEdit} /> },
        { key: 'certification', title: '技能证书信息', content: <SkillQual isEditPanel={isEdit} /> },
      ],
    },
    {
      key: 'teacherEthics',
      title: '师德信息',
      subMenu: [
        { key: 'ethics', title: '师德', content: <TeacherEthics isEditPanel={isEdit} /> },
        { key: 'punishment', title: '处分', content: <TeacherEthicsPunishment isEditPanel={isEdit} /> },
      ],
    },
    {
      key: 'educationTeaching',
      title: '教育教学信息',
      subMenu: [],
      content: <TearchEdu isEditPanel={isEdit} />,
    },
    {
      key: 'talentProjects',
      title: '入选人才项目信息',
      subMenu: [],
      content: <RecrVisit isEditPanel={isEdit} />,
    },
    {
      key: 'academicResults',
      title: '教学科研成果',
      subMenu: [
        {
          key: 'resultProject',
          title: '成果项目',
          content: <ScientificResearch isEditPanel={isEdit} achievement_type={RESEARCH_TYPE[0].value} />,
        },
        {
          key: 'resultWork',
          title: '成果著作',
          content: <ScientificResearch isEditPanel={isEdit} achievement_type={RESEARCH_TYPE[1].value} />,
        },
        {
          key: 'resultPaper',
          title: '成果论文',
          content: <ScientificResearch isEditPanel={isEdit} achievement_type={RESEARCH_TYPE[2].value} />,
        },
        {
          key: 'resultAward',
          title: '成果奖励',
          content: <ScientificResearch isEditPanel={isEdit} achievement_type={RESEARCH_TYPE[3].value} />,
        },
        {
          key: 'resultLiteraryWork',
          title: '成果文艺作品',
          content: <ScientificResearch isEditPanel={isEdit} achievement_type={RESEARCH_TYPE[4].value} />,
        },
        {
          key: 'resultPatent',
          title: '成果专利/著作',
          content: <ScientificResearch isEditPanel={isEdit} achievement_type={RESEARCH_TYPE[5].value} />,
        },
        {
          key: 'resultReport',
          title: '成果报告',
          content: <ScientificResearch isEditPanel={isEdit} achievement_type={RESEARCH_TYPE[6].value} />,
        },
        {
          key: 'resultCertificate',
          title: '成果医疗证书',
          content: <ScientificResearch isEditPanel={isEdit} achievement_type={RESEARCH_TYPE[7].value} />,
        },
        {
          key: 'resultStandard',
          title: '成果标准',
          content: <ScientificResearch isEditPanel={isEdit} achievement_type={RESEARCH_TYPE[8].value} />,
        },
        {
          key: 'resultStudentAward',
          title: '成果学生竞赛作品',
          content: <ScientificResearch isEditPanel={isEdit} achievement_type={RESEARCH_TYPE[9].value} />,
        },
      ],
    },
    {
      key: 'changeInfo',
      title: '变动信息',
      subMenu: [
        { key: 'borrowRecord', title: '借动记录', content: <BorrowInfo /> },
        { key: 'transferRecord', title: '调动记录', content: <TransferInfo /> },
        { key: 'schoolChange', title: '校内变动记录', content: <WorkChangeInfo /> },
      ],
    },
  ];

  const init = async () => {
    const resD = await TeachersSrv.detail(id);
    if (resD.success) {
      setForm(prevForm => ({
        ...prevForm,
        basicTop: { ...resD.data },
      }));
    }
    const resI = await TeachersSrv.info(id);
    if (resI.success) {
      if (resI.data.current_post_level) {
        resI.data.current_post_level = resI.data.current_post_level.split(',');
      }
      if (resI.data.health_condition) {
        resI.data.health_condition = resI.data.health_condition.split(',');
      }
      if (resI.data.highest_education) {
        resI.data.highest_education = resI.data.highest_education.split(',');
      }
      if (resI.data.current_post_type) {
        resI.data.current_post_type = resI.data.current_post_type.split(',');
      }
      if (resI.data.source_of_staff) {
        resI.data.source_of_staff = resI.data.source_of_staff.split(',');
      }
    }

    setForm(prevForm => ({
      ...prevForm,
      basicBody: { ...resI.data },
    }));
    // TODO: 接口未实现
    // const resII = await TeachersSrv.changeInfo(Number(id));
    // if (resII.success) {
    //   setChangeInfo(resII.data);
    // }
    console.log('form', form);
  };
  const renderProcess = () => {
    return changeInfo.map((item, index) => {
      switch (item.key) {
        case 'teacherinfo':
          return (
            <div>
              <div className="tit">基本信息</div>
              <ul>
                {item.change.map((it, idx) => {
                  return (
                    <li>
                      <Button
                        type="link"
                        onClick={() => {
                          setTabKey('1');
                        }}
                      >
                        {_.find(basicInfo[0].inputs, { name: it.key }).label}:
                        {_.find(basicInfo[0].inputs, { name: it.key }).renderOption
                          ? utils.findLabelsDeep(_.find(basicInfo[0].inputs, { name: it.key }).renderOption, it.val)
                          : it.val}
                      </Button>
                    </li>
                  );
                })}
              </ul>
            </div>
          );
        case 'teacher-learn-experience-all':
          return (
            <div>
              <div className="tit">学习经历</div>
              <ul>
                {item.change.map((it, idx) => {
                  return (
                    <li>
                      <Button
                        type="link"
                        onClick={() => {
                          setTabKey('2');
                        }}
                      >
                        {_.find(learnExpInfo[0].inputs, { name: it.key }).label}:
                        {_.find(learnExpInfo[0].inputs, { name: it.key }).renderOption
                          ? utils.findLabelsDeep(_.find(learnExpInfo[0].inputs, { name: it.key }).renderOption, it.val)
                          : it.val}
                      </Button>
                    </li>
                  );
                })}
              </ul>
            </div>
          );
        default:
          return <></>;
      }
    });
  };

  React.useEffect(() => {
    init();
  }, []);

  return (
    <PageContainer
      header={
        <>
          <Breadcrumb
            items={[
              {
                title: '在职教职工管理',
                onClick: e => {
                  navigator(`${getPathRoot()}/employed`);
                },
              },
              { title: '人员信息变更' },
            ]}
          />
          <Button
            style={{ marginLeft: 'calc(100% - 495px)' }}
            type="primary"
            onClick={() => {
              const elem: any = document.querySelectorAll('#baseForm .ant-form-item-control-input-content button')[0];
              elem.click();
            }}
          >
            提交
          </Button>
        </>
      }
    >
      <div className={styles.change_view}>
        <BasicTop
          onLoad={(form1, form2) => {
            setTopCntForm(form1);
            setTopPhotoForm(form2);
          }}
          isEdit={isEdit}
          formValue={form.basicTop}
          api={api.basicTop}
        />
        <Button
          style={{
            position: 'absolute',
            top: '420px',
            zIndex: '999',
            right: '50px',
          }}
          type="primary"
          onClick={() => setShowLogs(true)}
        >
          变更日志
        </Button>
        <Row>
          <Col span={changeInfo.length > 0 ? 18 : 24}>
            <MenuContent menus={menus} />
            {/* <Tabs
              onChange={(key: string) => {
                console.log(key);
                setTabKey(key);
              }}
              className={styles.tabs}
              type="card"
              activeKey={tabKey}
              items={[
                {
                  label: '基本信息',
                  key: '1',
                  children: (
                    <div id="baseForm">
                      <BasicBody
                        isEdit={isEdit}
                        buttonList={[<Button onClick={() => navigator(`${getPathRoot()}/employed`)}>返回</Button>]}
                        formValue={form.basicBody}
                        api={api.basicBody}
                      />
                    </div>
                  ),
                },
                {
                  label: '学习经历',
                  key: '2',
                  children: <LearnExp isEditPanel={isEdit} />,
                },
                {
                  label: '工作经历',
                  key: '3',
                  children: <WorkExp isEditPanel={isEdit} />,
                },
                {
                  label: '岗位聘任',
                  key: '4',
                  children: <PositionAppmt isEditPanel={isEdit} />,
                },
                {
                  label: '专业技术职位管理',
                  key: '5',
                  children: <ProTechMg isEditPanel={isEdit} />,
                },
                {
                  label: '教师资格',
                  key: '6',
                  children: <TeacherQual isEditPanel={isEdit} />,
                },
                {
                  label: '技能及资格',
                  key: '7',
                  children: <SkillQual isEditPanel={isEdit} />,
                },
                {
                  label: '师德',
                  key: '8',
                  children: <TeacherEthics isEditPanel={isEdit} />,
                },
                {
                  label: '教育教学',
                  key: '9',
                  children: <TearchEdu isEditPanel={isEdit} />,
                },
                {
                  label: '国内培训',
                  key: '10',
                  children: <DomesticTraining isEditPanel={isEdit} />,
                },
                {
                  label: '海外研修(访学)',
                  key: '11',
                  children: <OsResearch isEditPanel={isEdit} />,
                },
                {
                  label: '入选人才访学',
                  key: '12',
                  children: <RecrVisit isEditPanel={isEdit} />,
                },
                {
                  label: '年度考核',
                  key: '13',
                  children: <AnnualAssess isEditPanel={isEdit} />,
                },
                {
                  label: '教学科研成果及获奖信息',
                  key: '14',
                  children: <ScientificResearch isEditPanel={isEdit} />,
                },
                {
                  label: '调动信息',
                  key: '15',
                  children: <TransferInfo />,
                },
                {
                  label: '借动信息',
                  key: '16',
                  children: <BorrowInfo />,
                },
                {
                  label: '变动信息',
                  key: '17',
                  children: <WorkChangeInfo />,
                },
              ]}
            /> */}
          </Col>
          <Col span={changeInfo.length > 0 ? 6 : 0}>
            <div
              className={styles.change_process}
              style={{
                height: `calc(100%${tabKey === '1' ? ' - 120px' : ' - 20px'})`,
              }}
            >
              {renderProcess()}
            </div>
          </Col>
        </Row>
      </div>
      <Logs show={showLogs} onClose={() => setShowLogs(false)} title={topCntForm?.getFieldValue('teacher_name')} />
    </PageContainer>
  );
};

Groups.defaultProps = {
  isEdit: true,
};

export default Groups;
